<?php
$db = new Database;
$auth = Auth::getAuth('current_user');
$company_id = $auth['company_id'];
$user_id = $auth['id'];
$user_group = $auth['role'];
$user_groupType = $auth['role_type'];
if(isset($_POST['action'])){
    if($_POST['action']=="getFields"){
        $form_id = $_POST['id'];
        $getFields =  $db->query("SELECT * FROM tbform f LEFT JOIN tbfield_output fo ON f.id=fo.form_id WHERE form_id='$form_id'","array");
        $getForm =  $db->query("SELECT * FROM tbform f LEFT JOIN tbfield_output fo ON f.id=fo.form_id WHERE form_id='$form_id'","row");
        $uniqueId = 1;
        echo ftu_form($getForm['form_title'],$getForm['description'],$getForm['label_placement']);
        echo "<div class='mainContent' id='drag'>";
        foreach($getFields as $dataFields){
            // setField($uniqeID,$f_label,$f_size=null,$options=null,$sft=null,$f_layout=null,$name_format=null,$lb_desc=null)
            echo "<br />".$dataFields['ftu']($uniqueId,$dataFields['f_label'],$dataFields['f_size'],$dataFields['options'],$dataFields['sft'],$dataFields['f_layout'],$dataFields['name_format'],$dataFields['lb_desc'],$dataFields['f_type'],$dataFields['id']);
            $uniqueId++;
        }
        echo "</div>";
    }elseif($_POST['action']=="getobjectId"){
        $form_id = $_POST['id'];
        $getFields =  $db->query("SELECT * FROM tbform f LEFT JOIN tbfield_output fo ON f.id=fo.form_id WHERE form_id='$form_id'","array");
        $uniqueId = 1;
        foreach($getFields as $dataFields){
            $uniqueId++;
        }
        echo $uniqueId;
    }elseif($_POST['action']=="getObjectsToAppend"){
        $form_id = $_POST['id'];
        $formQuery = $db->query("SELECT * from tbform where id='$form_id'","row");
        echo "<h6>".$formQuery['form_title']."</h6>";
        ?>
        <p class="fontGray">Html Objects</p>
        <?php
        $query = $db->query("SELECT * from tbdefault_fields where fieldClassification=1 AND is_active='1'","array");
        $start = 1;
        foreach($query as $row){
            if($row['id']%2==1){
                echo "<p>";
            }
            if($row['icon']!="" && $row['btnType']==""){
            ?>
                <a title="<?php echo $row['field'];?>" class="btn btn-medium buttonLeft objects fontTahoma" ftc="<?php echo $row['ftc']; ?>" ><i class="<?php echo $row['icon']; ?> pull-left"></i> <?php echo $row['field']; ?></a>
            <?php
            }else{
            ?>
                <a title="<?php echo $row['field'];?>" class="btn btn-medium buttonLeft fontTahoma <?php echo $row['btnType']; ?> pull-left objects" ftc="<?php echo $row['ftc']; ?>"> <?php echo $row['field']; ?></a>
            <?php   
            }
            if($row['id']%2==0){
                echo "</p>";
            }
            $start++;
        }
        ?>
        <br /><br />
        <p class="fontGray" >Customize Objects</p>
        <?php
        $query = $db->query("SELECT * from tbdefault_fields where fieldClassification=2 AND is_active='1'","array");
        foreach($query as $row){
            if($row['id']%2==0){
                ?>
                <p>
                <?php
            }
            if($row['icon']!="" && $row['btnType']==""){
            ?>
                <a title="<?php echo $row['field'];?>" class="btn btn-medium buttonLeft objects fontTahoma" ftc="<?php echo $row['ftc']; ?>" ><i class="<?php echo $row['icon']; ?> pull-left"></i> <?php echo $row['field']; ?></a>
            <?php
            }else{
            ?>
                <a title="<?php echo $row['field'];?>" class="btn btn-medium buttonLeft fontTahoma <?php echo $row['btnType']; ?> pull-left objects" ftc="<?php echo $row['ftc']; ?>"> <?php echo $row['field']; ?></a>
            <?php
            }
            if($row['id']%2==1){
                ?>
                </p>
                <?php
            }
        }
        ?>
        <?php
    }elseif($_POST['action']=="getFormSettings"){
        $form_id = $_POST['id'];
        $formQuery = $db->query("SELECT * from tbform where id='$form_id'","row");
        echo "<h6>".$formQuery['form_title']."</h6>";
        ?>
        <label id='labelObject$id' class="fontGray">Form Name:</label>
                                    <input type="text" class="formName" value="Untitled Form"/>
                                <label id='labelObject$id' class="fontGray">Description:</label>
                                    <textarea class="formDesc">This is my form. Please fill it out. It's awesome!</textarea>                                       
                                        <label id='labelObject$id' class="fontGray">Label Placement:</label>
                                            <select class="select large" id="formLabelAlign" autocomplete="off" <!--onchange="updateForm($F(this), 'LabelAlign')"-->>
                                                <option id="allignleft" value="left">Left Aligned</option>
                                                <option id="alligncenter" value="center">Center Aligned</option>
                                                <option id="allignright" value="right">Right Aligned</option>
                                            </select>
            <?php
            //$getUserForm = $db->query("SELECT * FROM tbform_user where form_id='$form_id'","array");
            ?>
            <!--USER PER FORM-->
            <label id='labelObject' class="fontGray">Users:</label>
            <?php
            $checked = "";
            $getUserForm = $db->query("SELECT * FROM tbform_user where form_id='$form_id' and user='allUsers'","row");
            if($getUserForm['user']=="allUsers"){
                $checked="checked";
            }
            ?>
            <label class="checkbox"><input type="checkbox" <?php echo $checked; ?> class="usersForm allUsers" value="allUsers"/>All Users</label>
            <label><span class="icon-plus formUser" rel="getDepartmentFF" id="getDepartmentFF"></span> Department</label>
            <span class="span getDepartmentFF" style="display: none;">
                <?php
                $getDepartment = $db->query("SELECT * FROM tborgchart o LEFT JOIN tborgchartobjects oo on o.id=oo.orgChart_id WHERE o.status=1 and o.company_id='$company_id'","array");
                foreach($getDepartment as $setDepartment){
                    $getUserForm = $db->query("SELECT * FROM tbform_user where form_id='$form_id' and (user='".$setDepartment['role']."' or user='allUsers')","row");
                    $checked = "";
                    if($getUserForm['user']==$setDepartment['role'] || $getUserForm['user']=="allUsers"){
                        $checked="checked";
                    }
                    ?>
                    <label class="checkbox"><input type="checkbox" <?php echo $checked; ?>  class="usersForm usersType usersDept" value="<?php echo $setDepartment['role'] ?>"/><?php echo $setDepartment['role'] ?></label>
                    <?php   
                }
                ?>
            </span>
            <label><span class="icon-plus formUser" rel="getPositionFF" id="getPositionFF"></span> Position</label>
            <span class="span getPositionFF" style="display: none;">
                <?php
                $getPosition = $db->query("SELECT * FROM tbposition WHERE company_id='$company_id' and is_active=1","array");
                foreach($getPosition as $setPosition){
                    $getUserForm = $db->query("SELECT * FROM tbform_user where form_id='$form_id' and (user='pos_".$setPosition['id']."' or user='allUsers')","row");
                    $checked = "";
                    if($getUserForm['user']=="pos_".$setPosition['id'] || $getUserForm['user']=="allUsers"){
                        $checked="checked";
                    }
                    ?>
                    <label class="checkbox"><input type="checkbox" <?php echo $checked; ?> class="usersForm usersType" value="<?php echo "pos_".$setPosition['id'] ?>"/><?php echo $setPosition['position'] ?></label>
                    <?php
                }
                ?>
            </span>
            <label><span class="icon-plus formUser" rel="getUserFF" id="getUserFF"></span> User</label>
            <span class="span getUserFF" style="display: none;">
                <?php
                $getUsers = $db->query("SELECT * from tbuser where status = 1 and company_id = '$company_id' and is_active = 1","array");
                foreach($getUsers as $setUsers){
                    $getUserForm = $db->query("SELECT * FROM tbform_user where form_id='$form_id' and (user='".$setUsers['id']."' or user='allUsers')","row");
                    $checked = "";
                    if($getUserForm['user']==$setUsers['id'] || $getUserForm['user']=="allUsers"){
                        $checked="checked";
                    }
                    ?>
                    <label class="checkbox"><input type="checkbox" <?php echo $checked; ?> class="usersForm usersType" value="<?php echo $setUsers['id'] ?>"/><?php echo setName($setUsers['firstname'],"",$setUsers['lastname']); ?></label>
                    <?php
                }
                ?>
            </span>
            <!--END USER PER FORM-->
        <?php
    }elseif($_POST['action']=="saveEditForm"){
        //delete
        $oldform_id = $_POST['id'];
        $conditionDelete = array(
            "form_id"=>$oldform_id
            );
        $formDelete = array(
            "id"=>$oldform_id
        );
        //delete fields!!
        $db->delete("tbform",$formDelete);
        $db->delete("tbfield_output",$conditionDelete);
        $db->delete("tbchoices",$conditionDelete);
        //insert
        $label = explode(",",implode(",",$_POST['label']));
        $options = explode(",",implode(",",$_POST['options']));
        $sft = explode(",",implode(",",$_POST['sft'])); //sft = show field to?(admin or user)
        $fieldsize = explode(",",implode(",",$_POST['fieldsize'])); //field size
        $fieldlayout = explode(",",implode(",",$_POST['fieldlayout'])); //field layout
        $choicesPush = explode(",",implode(",",$_POST['choicesPush']));
        $formHeader = explode("`",$_POST['formHeader']); //form header
        $name_format = explode(",",implode(",",$_POST['name_format']));
        $fof = explode(",",implode(",",$_POST['fof']));
        $ftu = explode(",",implode(",",$_POST['ftu']));
        $objectType_array = explode(",",implode(",",$_POST['objectType_array']));
        $lb_desc_arr = explode(",",implode(",",$_POST['lb_desc_arr']));
        $timezone = "Asia/Manila";
        if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
        $query_form_counter = $db->query("SELECT * from tbform where company_id = '$company_id' and is_active=1","numrows");
        if($query_form_counter>=5){
            echo "forms excess";
        }else{
            //for form header
            $insert_tbform = array(
                "form_title"=>$formHeader[0],
                "description"=>$formHeader[1],
                "label_placement"=>$formHeader[2],
                "company_id"=>$company_id,
                "user_id"=>$user_id,
                "date_done"=>date("Y-m-d  H:i:s"),
                "is_active"=>1,
            );
            $form_id = $db->insert("tbform",$insert_tbform);
            $start_loop = 0;
            //for fields
            for($b=0;$b<count($label);$b++){
                //insert the fields
                $insert_tbfields = array(
                    "form_id"=>$form_id,
                    "fof"=>$fof[$b],
                    "ftu"=>$ftu[$b],
                    "f_label"=>$label[$b],
                    "f_size"=>$fieldsize[$b],
                    "options"=>$options[$b],
                    "sft"=>$sft[$b],
                    "f_layout"=>$fieldlayout[$b],
                    "name_format"=>$name_format[$b],
                    "f_type"=>$objectType_array[$b],
                    "lb_desc"=>$lb_desc_arr[$b]
                );
                $field_id = $db->insert("tbfield_output",$insert_tbfields);
                
                //for choices
                if($choicesPush[$b]!="0"){
                    $choice = substr($choicesPush[$b],0,strlen($choicesPush[$b])-1);
                    $choice = explode("`",$choice);
                    for($d=$start_loop;$d<count($choice);$d++){ //insert choices
                        $choice_check = explode(":",$choice[$d]);
                        $insert_tbchoices = array(
                            "field_id"=>$field_id,
                            "form_id"=>$form_id,
                            "choice_label"=>$choice_check[0],
                            "checked"=>$choice_check[1]
                        );
                        $db->insert("tbchoices",$insert_tbchoices);
                    }
                    $start_loop = count($choice);
                }
            }
        }
    }elseif($_POST['action']=="updateStatusDeactivate"){
        $id = $_POST['id'];
        $update = array(
            "is_active"=>0
            );
        $condition = array(
            "id"=>$id
            );
        $db->update("tbform",$update,$condition);
    }elseif($_POST['action']=="updateStatusActivate"){
        $id = $_POST['id'];
        $update = array(
            "is_active"=>1
            );
        $condition = array(
            "id"=>$id
            );
        $db->update("tbform",$update,$condition);
    }else if($_POST['action']=="deleteForm"){
        $id = $_POST['id'];
        $condition = array(
            "id"=>$id
        );
        $db->delete("tbform",$condition);
        $conditionField = array(
            "form_id"=>$id
        );
        $db->delete("tbfield_output",$condition);
        $db->delete("tbchoices",$condition);
    }else if($_POST['action']=="getWorkflowSettings"){
        $form_id = $_POST['id'];
        $formQuery = $db->query("SELECT * from tbform where id='$form_id'","row");
        echo "<h6>Workflow for ".$formQuery['form_title']."</h6>";
        ?>
        <h4>Work Flow Objects</h4>
            <label>Approver Type:</label>
            <select class="approverTypeWorkflow" style="margin-bottom: 0px;margin-right: 3px">
                <option value="0">--Select--</option>
                <option value="1">Position the Group</option>
                <option value="2">Position in the Company</option>
                <option value="3">Specific User</option>
            </select>
            <br /><br />
            <label>Approver:</label>
            <select class="approverWorkflow" style="">
                <option value="0">--Select Approver Type--</option>
            </select>
            <br /><br />
            <label>Approver Status:</label>
            <select class="approverWorkflowStatus" style="">
                <option value="1">For Review</option>
                <option value="2">Approver</option>
            </select>
            <br />
            
            <input type="button" class="btn shapes" id="worklow" rel="workflow" value="Add">
        <?php
    }else if($_POST['action']=="getWorkflow"){
        $form_id = $_POST['id'];
        $getWorkFlow = $db->query("SELECT workflow_id FROM tbform where id='$form_id'","row");
        $diagram_id = $getWorkFlow['workflow_id'];
        $selectObjects = $db->query("SELECT * from tbworflow_obects where worflow_id = '$diagram_id'","array");
        $counter = 1;
        foreach($selectObjects as $getObjects){
            $object_id = explode("_",$getObjects['object_id']);
            if($getObjects['role']=="END"){
                ?>
                <span class="appendShapes workflowObjects flowChartObject appendObjects newObj" style="left:<?php echo $getObjects['lefts']; ?>;top:<?php echo $getObjects['tops']; ?>;" rel="notAllowed" node-type="end" id="<?php echo $object_id[0]."_".$object_id[1]."_".$object_id[2]; ?>">
                <span id="spanText_<?php echo $object_id[1]; ?>" class="textHandle" style="cursor:pointer;position: absolute;margin: 5px;width: 60px;text-align: center;font-size: large">END</span>
                </span>
                <?php
                
            }else{
                if($getObjects['role']=="START"){
                    $addAttr = "node-type='start' rel='notAllowed'";
                    $addStyle = "font-size: large;";
                }else{
                    $addAttr = "node-type='approver' rel='approver'";
                    $addStyle = "";
                }
                ?>
                <span class="appendShapes workflowObjects flowChartObject appendObjects newObj" <?php echo $addAttr ?> style="left:<?php echo $getObjects['lefts']; ?>;top:<?php echo $getObjects['tops']; ?>;" diagram-type="workflow"  id="<?php echo $object_id[0]."_".$object_id[1]."_".$object_id[2]; ?>">
                <span id="spanText_<?php echo $object_id[1]; ?>" class="textHandle" style="<?php echo $addStyle; ?>cursor:pointer;position: absolute;margin: 5px;width: 60px;text-align: center;"><?php echo $getObjects['role']; ?></span><br />
                <span id="spanStatus_<?php echo $object_id[1]; ?>" class="textHandle" style="<?php echo $addStyle; ?>cursor:pointer;position: absolute;margin: 5px;min-width: 82px;text-align: center;"><?php echo $getObjects['status']; ?></span>
                  <span id="flow_<?php echo $object_id[1]."_".$object_id[2]; ?>" rel="1" class="fl_shapes flowChartObject"></span>
                  <span style="position:absolute" class="shapeSideButton_holder flowChartObject">
                      <span style="color:red;position:absolute;margin-left:-10px;width:10px;height:10px;padding-left:5px;margin-top:12px;background-color:black" class="right flowChartObject connector" id="right_<?php echo $object_id[1]."_".$object_id[2]; ?>"></span>
                  </span>
                </span>
                <?php
                $counter++;    
            }
        }
        $selectLines = $db->query("SELECT * from tbworkflow_line where worflow_id = '$diagram_id' and line_type=1","array");
        foreach($selectLines as $getLines){
            $arrayParent = explode("_",$getLines['master_id']); //split the parent id using the delimiter underscore "_"
            $arrayParent = "line_".$arrayParent[1]; //get the second array element of parent then add "line_" prefix
            $arrayChild = explode("_",$getLines['child_id']); //split the parent id using the delimiter underscore "_"
            $arrayChild = "line_".$arrayChild[1]; //get the second array element of child then add "line_" prefix
            $setClass = $arrayParent."-".$arrayChild; //concat the result of arrayChild and arrayParent
            ?>
            <span class="line <?php echo $setClass; ?> newLines" rel='' axis="<?php echo $getLines['axis']; ?>" line-type="<?php echo $getLines['line_type']; ?>" id="<?php echo $getLines['line_id']; ?>" master_id="<?php echo $getLines['master_id']; ?>" child_id="<?php echo $getLines['child_id']; ?>"
                                    style="margin-left:<?php echo $getLines['margin_lefts']; ?>;left:<?php echo $getLines['lefts']; ?>;width:<?php echo $getLines['widths']; ?>;margin-top:<?php echo $getLines['margin_tops']; ?>;top:<?php echo $getLines['tops']; ?>;
                                    position:absolute;height:<?php echo $getLines['heights']; ?>;background-color:black;"></span>
            <?php
        }
        $selectArrow = $db->query("SELECT * from tbworkflow_line where worflow_id = '$diagram_id' and line_type=2","array");
        foreach($selectArrow as $getLinesArrow){
            $arrayParent = explode("_",$getLinesArrow['master_id']); //split the parent id using the delimiter underscore "_"
            $arrayParent = "line_".$arrayParent[1]; //get the second array element of parent then add "line_" prefix
            $arrayChild = explode("_",$getLinesArrow['child_id']); //split the parent id using the delimiter underscore "_"
            $arrayChild = "line_".$arrayChild[1]; //get the second array element of child then add "line_" prefix
            $setClass = $arrayParent."-".$arrayChild; //concat the result of arrayChild and arrayParent
            echo setArrow($getLinesArrow['lefts'],$getLinesArrow['tops'],$setClass,$getLinesArrow['axis'],$getLinesArrow['line_id'],$getLinesArrow['master_id'],$getLinesArrow['child_id'],$getLinesArrow['line_type']);
        }
    }else if($_POST['action']=="getWorkflowUniqueID"){
        $form_id = $_POST['form_id'];
        $getWorkFlow = $db->query("SELECT workflow_id FROM tbform where id='$form_id'","row");
        $diagram_id = $getWorkFlow['workflow_id'];
        $selectObjects = $db->query("SELECT * from tbworflow_obects where worflow_id = '$diagram_id'","array");
        $arrayObjID = array();
        foreach($selectObjects as $dataObjects){
            $getMax = explode("_",$dataObjects['object_id']);
            array_push($arrayObjID,$getMax[1]);
        }
        echo max($arrayObjID)+1;
    }else if($_POST['action']=="saveUpdatedWorkFlow"){
        $form_id = $_POST['form_id'];
        $getWorkFlow = $db->query("SELECT workflow_id FROM tbform where id='$form_id'","row");
        $diagram_id = $getWorkFlow['workflow_id'];
        //FOR OBJECTS 
        $object_id = explode(",",implode(",",$_POST['object_id']));
        $object_tops = explode(",",implode(",",$_POST['object_tops']));
        $object_lefts = explode(",",implode(",",$_POST['object_lefts']));
        $object_role = explode(",",implode(",",$_POST['object_role']));
        $object_status = explode(",",implode(",",$_POST['object_status']));
        //FOR LINES
        $line_id = explode(",",implode(",",$_POST['line_id']));
        $master_id = explode(",",implode(",",$_POST['master_id_workflow']));
        $child_id = explode(",",implode(",",$_POST['child_id']));
        $line_tops = explode(",",implode(",",$_POST['line_tops']));
        $line_lefts = explode(",",implode(",",$_POST['line_lefts']));
        $line_heights = explode(",",implode(",",$_POST['line_heights']));
        $line_widths = explode(",",implode(",",$_POST['line_widths']));
        $line_margin_tops = explode(",",implode(",",$_POST['line_margin_tops']));
        $line_margin_lefts = explode(",",implode(",",$_POST['line_margin_lefts']));
        $line_axis = explode(",",implode(",",$_POST['line_axis']));
        $line_type = explode(",",implode(",",$_POST['line_type']));
        $origSeq = array();
        $newSeq = array();
        $objStartToReset = "";
        //INSERT TO TEMP LINES
        for($lines=0;$lines<count($line_id);$lines++){
            if($line_type[$lines]==2){
                $tempLines = array(
                    "workflow_id"=>$diagram_id,
                    "master_id"=>$master_id[$lines],
                    "child_id"=>$child_id[$lines],              
                    );
                $insertTempWorkflow = $db->insert("tbtemp_lines",$tempLines);
            }
        }
        //INSERT TO TEMP OBJECT
            for($obj=0;$obj<count($object_id);$obj++){
                $tempObj = array(
                    "workflow_id"=>$diagram_id,
                    "object_id"=>$object_id[$obj],
                    "role"=>$object_role[$obj],
                    );
                $insertObj = $db->insert("tbtemp_obj",$tempObj);
            }
        //"OLD SEQUENCE:";
        $loopRange = $db->query("select distinct(master_id) FROM tbworkflow_line where worflow_id = '$diagram_id'","numrows");
        for($a=0;$a<$loopRange;$a++){
            if($a==0){
                $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = 'flowspan_1_worklow' and worflow_id = '$diagram_id'","row");    
            }else{
                $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = '".$master['child_id']."' and worflow_id = '$diagram_id'","row");    
            }
            $queryApprover = $db->query("SELECT * FROM tbworflow_obects where object_id='".$master['child_id']."'","row");
            array_push($origSeq,$queryApprover['object_id']."<>".$queryApprover['role']);
        }
        //"NEW SEQUENCE";
        
        
        
        
        //get master
        $queryObject = $db->query("SELECT object_id from tbtemp_obj where workflow_id = '$diagram_id'","array");
        $queryRows = $db->query("SELECT object_id from tbtemp_obj where workflow_id = '$diagram_id'","numrows");
        $count = 0;
        $countError = array();
        $object = array();
        $topNode = "";
        $sequencialOrgChartNew = array();
        foreach($queryObject as $data){
            $queryLines = $db->query("SELECT DISTINCT(child_id) FROM tbtemp_lines where workflow_id = '$diagram_id'","array");
            foreach($queryLines as $dataLines){
                if($dataLines['child_id']!=$data['object_id']){
                    $count++;
                }
            }
            array_push($countError,$count);
            array_push($object,$data['object_id']);
            $count = 0;
        }
        $countMaster = 0;
        for($a=0;$a<$queryRows;$a++){
            if($countError[$a]+1==$queryRows){
                //echo $countError[$a];
                $topNode =  $object[$a];
                $countMaster++;
            }
        }
        
        $loopRange2 = $db->query("select distinct(master_id) FROM tbtemp_lines where workflow_id = '$diagram_id'","numrows");
        for($a=0;$a<$loopRange2;$a++){
            if($a==0){
                $master = $db->query("SELECT child_id FROM tbtemp_lines where master_id = 'flowspan_1_worklow' and workflow_id = '$diagram_id'","row");    
            }else{
                $master = $db->query("SELECT child_id FROM tbtemp_lines where master_id = '".$master['child_id']."' and workflow_id = '$diagram_id'","row");    
            }
            $queryApprover = $db->query("SELECT * FROM tbtemp_obj where object_id='".$master['child_id']."'","row");
            array_push($newSeq,$queryApprover['object_id']."<>".$queryApprover['role']);
        }
        //VALIDATION OF OLD AND NEW SEQUENCE
        $updateForm = false;
        for($v=0;$v<count($origSeq);$v++){
            $origSeqArray = explode("<>",$origSeq[$v]);
            $newSeqArray = explode("<>",$newSeq[$v]);
            if($origSeqArray[1]!=$newSeqArray[1]){
                $objStartToReset = $origSeqArray[0];
                $updateForm = true;
                break;
            }
        }
        //echo $countMaster;
        if($countMaster==1){
            //GET THE REQUEST ID
            $requestToReset = array();
            //DELETE OLD WORKFLOW OBJECTS AND LINES
            $deleteOld = array(
                "worflow_id"=>$diagram_id
                );
            $db->delete("tbworkflow_line",$deleteOld);
            $db->delete("tbworflow_obects",$deleteOld);
            //INSERT NEW WORKFLOW OBJECTS AND LINES
            //NODES OR OBJECTS
                for($newObj=0;$newObj<count($object_id);$newObj++){
                    $tempObj = array(
                        "worflow_id"=>$diagram_id,
                        "object_id"=>$object_id[$newObj],
                        "tops"=>$object_tops[$newObj],
                        "lefts"=>$object_lefts[$newObj],
                        "role"=>$object_role[$newObj],
                        "status"=>$object_status[$newObj]
                        );
                    $insertObj = $db->insert("tbworflow_obects",$tempObj);
                }
                //LINES
                for($lines=0;$lines<count($line_id);$lines++){
                    $workFlowLines = array(
                        "line_id"=>$line_id[$lines],
                        "worflow_id"=>$diagram_id,
                        "master_id"=>$master_id[$lines],
                        "child_id"=>$child_id[$lines],
                        "tops"=>$line_tops[$lines],
                        "lefts"=>$line_lefts[$lines],
                        "heights"=>$line_heights[$lines],
                        "widths"=>$line_widths[$lines],
                        "margin_tops"=>$line_margin_tops[$lines],
                        "margin_lefts"=>$line_margin_lefts[$lines],
                        "axis"=>$line_axis[$lines],
                        "line_type"=>$line_type[$lines],
                        );
                    $insertworkFlowLines = $db->insert("tbworkflow_line",$workFlowLines);
                }
            if($updateForm==true){
                $selectActiveRequest = $db->query("SELECT * FROM tbrequest_process rp LEFT JOIN tbrequest r on rp.request_id = r.id LEFT JOIN tbform f on r.form_id = f.id left join tbworkflow w on f.workflow_id = w.id where rp.wf_master_id = '$objStartToReset' and rp.status = 0 and w.id='$diagram_id'","array");
                foreach($selectActiveRequest as $dataActiveRequest){
                    //echo "Request_id: ".$dataActiveRequest['request_id']."\n";
                    array_push($requestToReset,$dataActiveRequest['request_id']);
                }
                $loopRange = $db->query("select distinct(master_id) FROM tbworkflow_line where worflow_id = '$diagram_id'","numrows");
                for($a=0;$a<$loopRange;$a++){
                    if($a==0){
                        $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = '$objStartToReset' and worflow_id = '$diagram_id'","row");    
                    }else{
                        $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = '".$master['child_id']."' and worflow_id = '$diagram_id'","row");    
                    }
                    $queryApprover = $db->query("SELECT * FROM tbworflow_obects where object_id='".$master['child_id']."'","row");
                    $selectActiveRequest = $db->query("SELECT * FROM tbrequest_process rp LEFT JOIN tbrequest r on rp.request_id = r.id LEFT JOIN tbform f on r.form_id = f.id left join tbworkflow w on f.workflow_id = w.id where rp.wf_master_id = '".$queryApprover['object_id']."' and rp.status = 0 and w.id='$diagram_id'","array");
                    foreach($selectActiveRequest as $dataActiveRequest){
                        array_push($requestToReset,$dataActiveRequest['request_id']);
                    }
                }
                //DELETE ALL REQUEST AFFECTED
                for($newReq=0;$newReq<count($requestToReset);$newReq++){
                    $deleteOldReq = array(
                        "request_id"=>$requestToReset[$newReq]
                        );
                    $db->delete("tbrequest_process",$deleteOldReq);
                }
                //INSERT THE FIRST APPROVER
                for($reqProc=0;$reqProc<count($requestToReset);$reqProc++){
                    $selectUser = $db->query("Select * FROM tbrequest r LEFT JOIN tbuser u on r.user_id = u.id WHERE r.id = ".$requestToReset[$reqProc]."","row");
                    $start = $db->query("SELECT child_id FROM tbworkflow_line where master_id = 'flowspan_1_worklow' and worflow_id = '$diagram_id'","row");
                    $getWorkFlowGroup = $db->query("SELECT * FROM tbworflow_obects where object_id='".$start['child_id']."' and worflow_id = '$diagram_id'","row");
                    $approverStatus = $getWorkFlowGroup['status'];
                    $valid = 1;
                    if(!empty($start['child_id'])){
                        //echo $getWorkFlowGroup['role'];
                        if($selectUser['role_type']==1){
                            $getActiveOrgChart = $db->query("SELECT id FROM tborgchart where is_active = 1 and company_id='$company_id' and status=1","row");
                            $getObjectID = $db->query("SELECT object_id from tborgchartobjects where role='".$selectUser['role']."' and orgChart_id='".$getActiveOrgChart['id']."'","row");
                            $getMasterObjectID = $db->query("SELECT master_id from tborgchartline where child_id='".$getObjectID['object_id']."' and orgChart_id='".$getActiveOrgChart['id']."'","row");
                            $getOrgChartGroup = $db->query("SELECT role from tborgchartobjects where object_id='".$getMasterObjectID['master_id']."' and orgChart_id='".$getActiveOrgChart['id']."'","row");
                            if($getOrgChartGroup['role']!=""){
                                if($getWorkFlowGroup['role']=="Head" || $getWorkFlowGroup['role']=="Assistant Head"){
                                    $approver = $getWorkFlowGroup['role']."_".$getOrgChartGroup['role'];
                                }else{
                                    $approver = $getWorkFlowGroup['role'];     
                                }
                            }else{
                                echo "0";
                                $valid = 0;
                            }
                        }else{
                             if($getWorkFlowGroup['role']=="Head" || $getWorkFlowGroup['role']=="Assistant Head"){
                                $approver = $getWorkFlowGroup['role']."_".$selectUser['role'];
                             }else{
                                $approver = $getWorkFlowGroup['role'];
                             }
                        }
                        $master_id = $getWorkFlowGroup['object_id'];
                    }else{
                        echo "0";
                        $valid = 0;
                    }
                    if($valid!=0){
                        $insertRequestProcess = array(
                                "request_id"=>$requestToReset[$reqProc],
                                "approver"=>$approver,
                                "wf_master_id"=>$master_id,
                                "approverStatus"=>$approverStatus,
                                "status"=>0
                        );
                        $requestProcess_id = $db->insert("tbrequest_process",$insertRequestProcess);
                    }
                }
            } 
        }else{
            echo "<?>"; //error workflow
        }
        //DELETE TEMPORARY DATA(LAST ACTION TO DO!)
        $deleteTemp = array(
            "workflow_id"=>$diagram_id
            );
        $db->delete("tbtemp_lines",$deleteTemp);
        $db->delete("tbtemp_obj",$deleteTemp);
    }
}
?>
